package com.keepers.repair.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.keepers.repair.R;
import com.keepers.repair.activity.BaseActivity;
import com.keepers.repair.activity.MainNewActivity;
import com.keepers.repair.activity.SOSMovieActivity;
import com.keepers.repair.aidl.IMainAidlInterface;
import com.keepers.repair.aidl.IPlayAidlCallback;
import com.keepers.repair.helper.IntentHelper;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.model.RepairModel;
import com.keepers.repair.model.UserModel;
import com.keepers.repair.net.DataLoader;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.CollectionUtil;
import com.keepers.repair.utils.UtilsKt;
import com.keepers.repair.view.IntercomButton;
import com.keepers.repair.view.OnIntercomListener;
import com.keepers.repair.view.TitleBar;
import com.keepers.repair.view.UPMarqueeView;
import com.keepers.repair.view.bindview.OnSimpleBindData;
import com.keepers.repair.view.bindview.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

/**
 * auth aboom
 * date 2018/10/22
 */
public class HomeFragment extends BaseFragment {

    private boolean        isImmersiveStatusBar;
    private long           preMills;
    private UPMarqueeView  upMarqueeView;
    private TextView       taskInfo;
    private LinearLayout   networkLayout;
    private IntercomButton intercomButton;
    private boolean isCreate;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            this.isImmersiveStatusBar = ((BaseActivity) context).isImmersiveStatusBar;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getActivity() == null) {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
        isCreate= true;
        LogUtil.e("HomeFragment onCreateView");
        IMainAidlInterface iMainAidlInterface = ((MainNewActivity) getActivity()).iMainAidlInterface;

        View view = ff(R.layout.fragment_home);
        if (isImmersiveStatusBar) {
            f(view, R.id.status_bar).setVisibility(View.VISIBLE);
        }
        String groupName = SpHelper.getLoginUserInfo().GroupName;
        TextView talkStatusText = f(view, R.id.talk_status_text);
        ImageView talkStatusIcon = f(view, R.id.talk_status_icon);
        networkLayout = f(view, R.id.network_disconnect_part);
        TitleBar titleBar = f(view, R.id.title_bar);
        titleBar.setRightIcon(R.drawable.contact_icon_offline, v -> IntentHelper.goContacts(getActivity()));
        titleBar.initializeHeaderNo(groupName);
        upMarqueeView = f(view, R.id.marquee);
        taskInfo = f(view, R.id.task_info);
        intercomButton = f(view, R.id.intercom);
        intercomButton.setOnIntercomListener(new OnIntercomListener() {
            @Override
            public void onStartRecord() {
                talkStatusIcon.setImageResource(R.drawable.ic_media_talk);
                talkStatusText.setText("我...");
            }

            @Override
            public void onFinishedRecord(String audioPath, long s) {
                if (!UtilsKt.isNetworkConnected()) {
                    return;
                }
                talkStatusIcon.setImageResource(R.drawable.ic_media_idle);
                talkStatusText.setText("空闲...");
                if (!TextUtils.isEmpty(audioPath)) {
                    String str = UtilsKt.encodeBase64File(audioPath);
                    UserModel loginUserInfo = SpHelper.getLoginUserInfo();
                    String[] fileNames = audioPath.split(File.separator);
                    rxHelper.pend(DataLoader.uploadChatVoice(loginUserInfo.Gid, loginUserInfo.GroupGid, str, fileNames[fileNames.length - 1], 12, s1 -> {
                        if (s1 == null) {
                            return;
                        }
//                        RepApplication.getApp().sendVoice(s1);
                        if (iMainAidlInterface != null) {
                            try {
                                iMainAidlInterface.sendVoice(s1);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }));
                }
                if (getActivity() != null) {
                    getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            }

            @Override
            public void onTimeShort() {
                AlertToast.show("录制时间过短...");
                talkStatusIcon.setImageResource(R.drawable.ic_media_idle);
                talkStatusText.setText("空闲...");
            }
        });


//        RepApplication.getApp().setPlayCallback((userName, playPath) -> {
//            Log.e("aa", " playName = " + userName);
//            UtilsKt.safelyTask(() -> {
//                if (TextUtils.isEmpty(userName)) {
//                    intercomButton.setIntercomRecording(false);
//                    talkStatusIcon.setImageResource(R.drawable.ic_media_idle);
//                    talkStatusText.setText("空闲...");
//                } else {
//                    intercomButton.setIntercomRecording(true);
//                    talkStatusIcon.setImageResource(R.drawable.ic_media_listen);
//                    talkStatusText.setText(userName + "在讲话...");
//                }
//            });
//        });
//        RepApplication.getApp().setNotNetworkCallback(networkConnected ->
//                UtilsKt.safelyTask(() -> {
//                    if (networkConnected) {
//                        networkLayout.setVisibility(View.GONE);
//                    } else {
//                        networkLayout.setVisibility(View.VISIBLE);
//                    }
//                    intercomButton.setNetworkConnected(networkConnected);
//                }));

        if (iMainAidlInterface != null) {
            try {
                iMainAidlInterface.setPlayCallback(new IPlayAidlCallback.Stub() {
                    @Override
                    public void onPlay(String playName, String playPath) {
                        Log.e("aa", " playName = " + playName);
                        UtilsKt.safelyTask(() -> {
                            if (TextUtils.isEmpty(playName)) {
                                intercomButton.setIntercomRecording(false);
                                talkStatusIcon.setImageResource(R.drawable.ic_media_idle);
                                talkStatusText.setText("空闲...");
                            } else {
                                intercomButton.setIntercomRecording(true);
                                talkStatusIcon.setImageResource(R.drawable.ic_media_listen);
                                talkStatusText.setText(playName + "在讲话...");
                            }
                        });
                    }
                });
//                iMainAidlInterface.setNetWorkCallback(new INotNetworkCallback.Stub() {
//                    @Override
//                    public void callback(boolean networkConnected) {
////                        AlertToast.show("网络发生变化 1 " + networkConnected);
//                        LogUtil.e("网络发生变化 1 " + networkConnected);
//                        UtilsKt.safelyTask(() -> {
//                            AlertToast.show("网络发生变化  " + networkConnected);
//                            if (networkConnected) {
//                                networkLayout.setVisibility(View.GONE);
//                            } else {
//                                networkLayout.setVisibility(View.VISIBLE);
//                            }
//                            intercomButton.setNetworkConnected(networkConnected);
//                        });
//                    }
//                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        f(view, R.id.right_bottom_click).setOnClickListener(v -> {
            try {
                iMainAidlInterface.sendMessage("我是文字...我是文字");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
//            RepApplication.getApp().sendMessage("我是文字...");
        });
        f(view, R.id.sos).setOnClickListener(v -> {
            long currentMills = System.currentTimeMillis();
            if (currentMills - preMills > 1500) {
                AlertToast.show("再次点击将进入报警模式...");
                preMills = currentMills;
            } else {
                startActivity(new Intent(getActivity(), SOSMovieActivity.class));
            }
        });
        return view;
    }

    public void networkCall(boolean networkConnected) {
        if (isCreate && getUserVisibleHint()) {
            if (networkConnected) {
                networkLayout.setVisibility(View.GONE);
            } else {
                networkLayout.setVisibility(View.VISIBLE);
            }
            intercomButton.setNetworkConnected(networkConnected);
        }
    }

//    private void initNetworkReceiver() {
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        registerReceiver(netWorkStateReceiver, filter);
//    }

    @Override
    public void onResume() {
        super.onResume();
        networkCall(UtilsKt.isNetworkConnected());
        getTask();
    }

    private void getTask() {
        UserModel loginUserInfo = SpHelper.getLoginUserInfo();
        rxHelper.pend(DataLoader.getRepairList(loginUserInfo.Gid, loginUserInfo.GroupGid, o -> {
            if (o == null || o.RepairTableList == null) {
                List<RepairModel> repairModels = SpHelper.getRepairModels();
                if (CollectionUtil.isNotEmpty(repairModels)) {
                    bindHomeTaskInfo(repairModels);
                }
                return;
            }
            List<RepairModel> repairTableList = o.RepairTableList;
            SpHelper.setRepairModels(repairTableList);
            bindHomeTaskInfo(repairTableList);
        }));
    }

    private void bindHomeTaskInfo(List<RepairModel> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        List<RepairModel> repairModels = Observable.fromIterable(list)
                .filter(repairModel -> repairModel.RIsState == 1).toList().blockingGet();
        if (CollectionUtil.isEmpty(repairModels)) {
            taskInfo.setVisibility(View.VISIBLE);
        } else {
            taskInfo.setVisibility(View.GONE);
        }
        upMarqueeView.setAdapter(R.layout.item_hone_task_info, repairModels, new OnSimpleBindData<RepairModel>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onBind(int pos, int itemCount, RepairModel repairModel, ViewHolder holder) {
                TextView itemTaskName = holder.getView(R.id.item_task_name);
                itemTaskName.setText("维修信息：" + repairModel.RepairInfor);
                TextView itemTaskTime = holder.getView(R.id.item_task_time);
                itemTaskTime.setText("提交时间：" + repairModel.SubmitTime);
                TextView itemTaskStatis = holder.getView(R.id.item_task_status);
                itemTaskStatis.setText("任务状态：未检修");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isCreate = false;
        LogUtil.e("HomeFragment onDestroy");
    }
}
